package com.abel.quiz.security;/**
 * Created by abel.lin on 2017/8/7.
 */

import com.abel.quiz.common.vo.AjaxResp;
import com.abel.quiz.vo.UserInfoDomain;
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author abel.lin
 * @date_time 2017/8/7 11:35
 * @description
 */
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String targetUrl = getDefaultTargetUrl();
        SavedRequest savedRequest = this.requestCache.getRequest(request, response);
        if(savedRequest != null){
            targetUrl = savedRequest.getRedirectUrl();
        }

        //如果是ajax请求则返回json，不是ajax请求则按默认执行
        if(AjaxResp.isAjax(request)){
            AjaxResp resp = new AjaxResp(AjaxResp.CodeArgs.OK);
            resp.setData(targetUrl);
            resp.toWriter(response);
        }else {
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
